package zucc.lcj.android_finalwork.help;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;

import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

import zucc.lcj.android_finalwork.FriendsActivity;
import zucc.lcj.android_finalwork.LoginActivity;
import zucc.lcj.android_finalwork.MyDatabaseHelper;
import zucc.lcj.android_finalwork.R;
import zucc.lcj.android_finalwork.guide.GuideActivity;
import zucc.lcj.android_finalwork.me.MeActivity;
import zucc.lcj.android_finalwork.me.StandardActivity;
import zucc.lcj.android_finalwork.stars.StarsActivity;

public class HelpActivity extends AppCompatActivity {
    //    列出帖子
    private List<zucc.lcj.android_finalwork.help.Message> messagelist = new ArrayList<>();
    private RecyclerView textlist;
    //    搜索帖子
    private List<zucc.lcj.android_finalwork.help.Message> messageSearchlist = new ArrayList<>();
    private RecyclerView textSeacrchlist;
    //    排行榜
    private MyDatabaseHelper dbHelper;
    private String[] name=new String[3];
    private String first_name,second_name,third_name;
    TextView help_first_name,help_second_name,help_third_name;
    private String first_url,second_url,third_url;
    ImageView help_first_img,help_second_img,help_third_img;
    protected static final int CHANGE_UI = 1;
    protected static final int ERROR = 2;
    private String searchs;
    //    发布帖子
    ImageButton add;
    //    搜索
    EditText search;
    Button searchbtn,searchexit;

    // 主线程创建消息处理器
    private Handler handler1 = new Handler() {
        @SuppressLint("HandlerLeak")
        public void handleMessage(android.os.Message msg) {
            if (msg.what == CHANGE_UI) {
                Bitmap bitmap = (Bitmap) msg.obj;
                help_first_img.setImageBitmap(bitmap);
            } else if (msg.what == ERROR) {
                Toast.makeText(HelpActivity.this, "显示图片错误",
                        Toast.LENGTH_SHORT).show();
            }
        }
    };
    // 主线程创建消息处理器
    private Handler handler2 = new Handler() {
        @SuppressLint("HandlerLeak")
        public void handleMessage(android.os.Message msg) {
            if (msg.what == CHANGE_UI) {
                Bitmap bitmap = (Bitmap) msg.obj;
                help_second_img.setImageBitmap(bitmap);
            } else if (msg.what == ERROR) {
                Toast.makeText(HelpActivity.this, "显示图片错误",
                        Toast.LENGTH_SHORT).show();
            }
        }
    };
    // 主线程创建消息处理器
    private Handler handler3 = new Handler() {
        @SuppressLint("HandlerLeak")
        public void handleMessage(android.os.Message msg) {
            if (msg.what == CHANGE_UI) {
                Bitmap bitmap = (Bitmap) msg.obj;
                help_third_img.setImageBitmap(bitmap);
            } else if (msg.what == ERROR) {
                Toast.makeText(HelpActivity.this, "显示图片错误",
                        Toast.LENGTH_SHORT).show();
            }
        }
    };

    @SuppressLint("Range")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_help);
        dbHelper = new MyDatabaseHelper(this,"UserStore.db",null,1);

//        搜索
        search = (EditText) findViewById(R.id.help_search);
        searchbtn = (Button) findViewById(R.id.help_searchbtn);
        searchbtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                searchs=search.getText().toString();
                System.out.println("searchs+"+searchs);
                initSearchMessage();
                textSeacrchlist = findViewById(R.id.textRecycleView);
                textSeacrchlist.setLayoutManager(new LinearLayoutManager(HelpActivity.this));
                textSeacrchlist.setAdapter(new HelpAdapter(messageSearchlist,HelpActivity.this));
            }
        });
        searchexit = (Button) findViewById(R.id.help_searchexit);
        searchexit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(HelpActivity.this, HelpActivity.class);
                startActivity(intent);
            }
        });



//        列出帖子
        initMessage();//添加信息
        textlist = findViewById(R.id.textRecycleView);
        textlist.setLayoutManager(new LinearLayoutManager(HelpActivity.this));
        textlist.setAdapter(new HelpAdapter(messagelist,HelpActivity.this));

//        发布贴
        add = (ImageButton) findViewById(R.id.help_add);
        add.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent();
                intent.setClass(HelpActivity.this, HelpAddActivity.class);
                startActivity(intent);
            }
        });

//        排行榜
        help_first_name = (TextView) findViewById(R.id.help_first_name);
        help_second_name = (TextView) findViewById(R.id.help_second_name);
        help_third_name = (TextView) findViewById(R.id.help_third_name);

        SQLiteDatabase db = dbHelper.getWritableDatabase();
        String sql="select * from UserInfo order by helpNum desc LIMIT 3";
        Cursor cursor = db.rawQuery(sql,null);
        int i=0;
        if (cursor.moveToFirst()){
            do{
                name[i]=cursor.getString(cursor.getColumnIndex("user_name"));
                System.out.println("i "+i);
                System.out.println("name "+name[i]);
                i++;
            }while (cursor.moveToNext());
        }
        first_name=name[0];
        help_first_name.setText(first_name);
//        System.out.println("name1 "+first_name);
        second_name=name[1];
        help_second_name.setText(second_name);
//        System.out.println("name2 "+second_name);
        third_name=name[2];
        help_third_name.setText(third_name);
//        System.out.println("name3 "+third_name);

        help_first_img = (ImageView) findViewById(R.id.help_first_photo) ;
        help_second_img = (ImageView) findViewById(R.id.help_second_photo) ;
        help_third_img = (ImageView) findViewById(R.id.help_third_photo) ;

        Cursor cursorImg1 = db.rawQuery("select * from UserInfo where user_name=?",new String[]{first_name});
        if (cursorImg1.moveToFirst()){
            first_url=cursorImg1.getString(cursorImg1.getColumnIndex("user_header"));
        }
        Cursor cursorImg2 = db.rawQuery("select * from UserInfo where user_name=?",new String[]{second_name});
        if (cursorImg2.moveToFirst()){
            second_url=cursorImg2.getString(cursorImg2.getColumnIndex("user_header"));
        }
        Cursor cursorImg3 = db.rawQuery("select * from UserInfo where user_name=?",new String[]{third_name});
        if (cursorImg3.moveToFirst()){
            third_url=cursorImg3.getString(cursorImg3.getColumnIndex("user_header"));
        }
        if (first_url!= null&&second_url!=null&&third_url!=null) {
            //子线程请求网络,Android4.0以后访问网络不能放在主线程中
            if (first_url.equals("https://bkimg.cdn.bcebos.com/pic/63d0f703918fa0ec08faacc53fde4eee3d6d54fb6deb?x-bce-process=image/watermark,image_d2F0ZXIvYmFpa2UxODA=,g_7,xp_5,yp_5/format,f_auto")){
                new Thread() {
                    private HttpURLConnection conn;
                    private Bitmap bitmap;

                    public void run() {
                        // 连接服务器 get 请求 获取图片
                        try {
                            //创建URL对象
                            URL url = new URL(first_url);
                            // 根据url 发送 http的请求
                            conn = (HttpURLConnection) url.openConnection();
                            // 设置请求的方式
                            conn.setRequestMethod("GET");
                            //设置超时时间
                            conn.setConnectTimeout(5000);
                            // 得到服务器返回的响应码
                            int code = conn.getResponseCode();
                            //请求网络成功后返回码是200
                            if (code == 200) {
                                //获取输入流
                                InputStream is = conn.getInputStream();
                                //将流转换成Bitmap对象
                                bitmap = BitmapFactory.decodeStream(is);
                                //将更改主界面的消息发送给主线程
                                Message msg = new Message();
                                msg.what = CHANGE_UI;
                                msg.obj = bitmap;
                                handler1.sendMessage(msg);
                            } else {
                                //返回码不等于200 请求服务器失败
                                Message msg = new Message();
                                msg.what = ERROR;
                                handler1.sendMessage(msg);
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                            Message msg = new Message();
                            msg.what = ERROR;
                            handler1.sendMessage(msg);
                        }
                        //关闭连接
                        conn.disconnect();
                    }
                }.start();
            }
            else {
                Bitmap bitmap = BitmapFactory.decodeFile(first_url);
                help_first_img.setImageBitmap(bitmap);
            }

            if (second_url.equals("https://bkimg.cdn.bcebos.com/pic/63d0f703918fa0ec08faacc53fde4eee3d6d54fb6deb?x-bce-process=image/watermark,image_d2F0ZXIvYmFpa2UxODA=,g_7,xp_5,yp_5/format,f_auto")){
                new Thread() {
                    private HttpURLConnection conn;
                    private Bitmap bitmap;

                    public void run() {
                        // 连接服务器 get 请求 获取图片
                        try {
                            //创建URL对象
                            URL url = new URL(second_url);
                            // 根据url 发送 http的请求
                            conn = (HttpURLConnection) url.openConnection();
                            // 设置请求的方式
                            conn.setRequestMethod("GET");
                            //设置超时时间
                            conn.setConnectTimeout(5000);
                            // 得到服务器返回的响应码
                            int code = conn.getResponseCode();
                            //请求网络成功后返回码是200
                            if (code == 200) {
                                //获取输入流
                                InputStream is = conn.getInputStream();
                                //将流转换成Bitmap对象
                                bitmap = BitmapFactory.decodeStream(is);
                                //将更改主界面的消息发送给主线程
                                Message msg = new Message();
                                msg.what = CHANGE_UI;
                                msg.obj = bitmap;
                                handler2.sendMessage(msg);
                            } else {
                                //返回码不等于200 请求服务器失败
                                Message msg = new Message();
                                msg.what = ERROR;
                                handler2.sendMessage(msg);
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                            Message msg = new Message();
                            msg.what = ERROR;
                            handler2.sendMessage(msg);
                        }
                        //关闭连接
                        conn.disconnect();
                    }
                }.start();
            }
            else {
                System.out.println("else2");
                Bitmap bitmap = BitmapFactory.decodeFile(second_url);
                help_second_img.setImageBitmap(bitmap);
            }

            if (third_url.equals("https://bkimg.cdn.bcebos.com/pic/63d0f703918fa0ec08faacc53fde4eee3d6d54fb6deb?x-bce-process=image/watermark,image_d2F0ZXIvYmFpa2UxODA=,g_7,xp_5,yp_5/format,f_auto")){
                new Thread() {
                    private HttpURLConnection conn;
                    private Bitmap bitmap;

                    public void run() {
                        // 连接服务器 get 请求 获取图片
                        try {
                            //创建URL对象
                            URL url = new URL(third_url);
                            // 根据url 发送 http的请求
                            conn = (HttpURLConnection) url.openConnection();
                            // 设置请求的方式
                            conn.setRequestMethod("GET");
                            //设置超时时间
                            conn.setConnectTimeout(5000);
                            // 得到服务器返回的响应码
                            int code = conn.getResponseCode();
                            //请求网络成功后返回码是200
                            if (code == 200) {
                                //获取输入流
                                InputStream is = conn.getInputStream();
                                //将流转换成Bitmap对象
                                bitmap = BitmapFactory.decodeStream(is);
                                //将更改主界面的消息发送给主线程
                                Message msg = new Message();
                                msg.what = CHANGE_UI;
                                msg.obj = bitmap;
                                handler3.sendMessage(msg);
                            } else {
                                //返回码不等于200 请求服务器失败
                                Message msg = new Message();
                                msg.what = ERROR;
                                handler3.sendMessage(msg);
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                            Message msg = new Message();
                            msg.what = ERROR;
                            handler3.sendMessage(msg);
                        }
                        //关闭连接
                        conn.disconnect();
                    }
                }.start();
            }
            else {
                System.out.println("else2");
                Bitmap bitmap = BitmapFactory.decodeFile(third_url);
                help_third_img.setImageBitmap(bitmap);
            }
        }

        ImageView bar_1 = (ImageView) findViewById(R.id.bar_1);
        ImageView bar_2 = (ImageView) findViewById(R.id.bar_2);
        ImageView bar_3 = (ImageView) findViewById(R.id.bar_3);
        ImageView bar_4 = (ImageView) findViewById(R.id.bar_4);
        ImageView bar_5 = (ImageView) findViewById(R.id.bar_5);
        bar_1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent();
                intent.setClass(HelpActivity.this, FriendsActivity.class);
                startActivity(intent);
            }
        });
        bar_3.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent();
                intent.setClass(HelpActivity.this, GuideActivity.class);
                startActivity(intent);
            }
        });
        bar_5.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent();
                intent.setClass(HelpActivity.this, MeActivity.class);
                startActivity(intent);
            }
        });
        bar_4.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent();
                intent.setClass(HelpActivity.this, StarsActivity.class);
                startActivity(intent);
            }
        });



    }

    @SuppressLint("Range")
    private void initMessage(){
        String title,content,state,photo,userPost,userHelp,time;
        SQLiteDatabase db = dbHelper.getWritableDatabase();
        Cursor cursor = db.rawQuery("select * from Help where help_state=?",new String[]{"未完成"});
        if (cursor.moveToFirst()){
            do{
                title=cursor.getString(cursor.getColumnIndex("help_title"));
                title="           "+title;
                content=cursor.getString(cursor.getColumnIndex("help_content"));
                state=cursor.getString(cursor.getColumnIndex("help_state"));
                photo=cursor.getString(cursor.getColumnIndex("help_photo"));
                String sql="select * from UserInfo where user_id="+ LoginActivity.global_login_user_id;
                Cursor cursor1 = db.rawQuery(sql,null);
                cursor1.moveToFirst();
                userPost=cursor1.getString(cursor1.getColumnIndex("user_name"));
                time=cursor.getString(cursor.getColumnIndex("help_time"));
                zucc.lcj.android_finalwork.help.Message test=new zucc.lcj.android_finalwork.help.Message(title,content,state,userPost,time,photo);
                messagelist.add(test);
            }while (cursor.moveToNext());
        }
    }

    @SuppressLint("Range")
    private void initSearchMessage(){
        String title,content,state,photo,userPost,userHelp,time;
        SQLiteDatabase db = dbHelper.getWritableDatabase();
        String sql1="select * from Help where help_state ='未完成' and (help_title LIKE '%"+searchs+"%' or help_content Like '%"+searchs+"%')";
        System.out.println("startSearch");
        Cursor cursor = db.rawQuery(sql1,null);
        if (cursor.moveToFirst()){
            do{
                title=cursor.getString(cursor.getColumnIndex("help_title"));
                title="           "+title;
                content=cursor.getString(cursor.getColumnIndex("help_content"));
                state=cursor.getString(cursor.getColumnIndex("help_state"));
                photo=cursor.getString(cursor.getColumnIndex("help_photo"));
                String sql="select * from UserInfo where user_id="+ LoginActivity.global_login_user_id;
                Cursor cursor1 = db.rawQuery(sql,null);
                cursor1.moveToFirst();
                userPost=cursor1.getString(cursor1.getColumnIndex("user_name"));
                time=cursor.getString(cursor.getColumnIndex("help_time"));
                zucc.lcj.android_finalwork.help.Message test=new zucc.lcj.android_finalwork.help.Message(title,content,state,userPost,time,photo);
                messageSearchlist.add(test);
                System.out.println("searchtitle+"+title);
            }while (cursor.moveToNext());
        }
    }
}

